#include "mainwindow.h"
#include "ui_mainwindow.h"

#include<QDebug>
#include<QFileDialog>
#include<QFile>


MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    this->setWindowTitle("简单的记事本操作");

    //添加状态栏
    statusBar = new QStatusBar();
    this->setStatusBar(statusBar);


    //创建菜单栏
    QMenuBar* menuBar = this->menuBar();
    this->setMenuBar(menuBar);

    //创建菜单
    QMenu* menu = new QMenu("文件");
    menuBar->addMenu(menu);

    //添加菜单项
    QAction* action = new QAction("打开");
    QAction* action2 = new QAction("保存");
    menu->addAction(action);
    menu->addAction(action2);

    //给菜单项连接槽函数
    connect(action,&QAction::triggered,this,&MainWindow::handle_open);
    connect(action2,&QAction::triggered,this,&MainWindow::handle_save);

    //创建文本编辑框
    edit = new QTextEdit(this);
    this->setCentralWidget(edit);

}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::handle_open()
{
//    qDebug()<<"打开文件";
//    statusBar->showMessage("打开文件",0);

    //弹出“打开文件对话框”
    QString path = QFileDialog::getOpenFileName(this,"打开文件");

    //在状态栏中显示路径
    statusBar->showMessage(QString("当前路径：")+path);

    //创建QFile对象，打开文件
    QFile file(path);
    bool ret = file.open(QFile::ReadOnly);
    if(!ret)
    {
        statusBar->showMessage(path+QString("打开失败"));
        return;
    }
    //读取数据
     QString text = file.readAll();
    file.close();

    //把读取到的文本转移到编辑框

    this->setCentralWidget(edit);
    edit->setPlainText(text);

}

void MainWindow::handle_save()
{
//    qDebug()<<"保存文件";
//    statusBar->showMessage("保存文件",0);

    //获取edit的数据

    this->setCentralWidget(edit);
    QString text = edit->toPlainText();

    //弹出保存文件对话框
    QString path = QFileDialog::getSaveFileName(this,"保存文件");



    //在状态栏中显示路径
    statusBar->showMessage(QString("当前路径：")+path);


    //根据选择的路径创建一个文件对象，打开文件
    QFile file(path);
    bool ret = file.open(QFile::WriteOnly);
    if(!ret)
    {
        //文件打开失败
        statusBar->showMessage(path+QString("文件打开失败"));
        return;
    }
    file.write(text.toUtf8());
    file.close();

}

